package com.esiea.contactmanager.controller;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.esiea.contactmanager.model.Adress;
import com.esiea.contactmanager.model.AdressBook;
import com.esiea.contactmanager.model.Contact;

/**
 * Handles requests for the application home page.
 */
@Controller
@SessionAttributes
public class MainController {
	
	private static final Logger logger = LoggerFactory.getLogger(MainController.class);
	
	private AdressBook addressBook;
	
	private Contact curentContact=null;
	
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = {"/","/index"}, method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! the client locale is "+ locale.toString());
		
		Contact toto=new Contact();
		toto.setFirstName("toto");
		toto.setId(0);
		addressBook.addContact(toto);
		model.addAttribute("contacts", addressBook.getContactList());
		return "index";
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public String delete(@RequestBody String s,Locale locale, Model model) {
		logger.info(s.substring(0,s.indexOf('&')));
		logger.info(s);
		boolean found = true;
		List<Integer> indexList = new ArrayList<Integer>();
		
		while(found == true)
		{
			String tmp = s.substring(0,s.indexOf('&'));
			s = s.substring(s.indexOf('&') + 1);
			
			if(tmp == null)
			{
				found = false;
				break;
			}
			
			String tmp3 = tmp.substring(5, tmp.indexOf('='));

			int index = Integer.decode(tmp3);
			
			indexList.add(index);
			
			
		}
		
		for(int i=0;i<indexList.size();i++)
		{
			for(int j = 0; j<indexList.size(); j++)
			{
				if(indexList.get(j) > indexList.get(i))
					indexList.set(j, indexList.get(j) - 1);
			}
		} 
		
		while(indexList.size() > 0)
		{
			int min = indexList.get(0), indexMin = -1;
			
			for(int l = 0; l<indexList.size(); l++)
			{
				int tmp = indexList.get(l);
				
				if(min > tmp)
				{
					min = tmp;
					indexMin = l;
				}
				
				indexList.remove(indexMin);
				addressBook.removeContactById(min);	
			}
			
		}
		
		return "redirect:index";
	}
	
	@RequestMapping(value = "/editContact")
	public String editdisplay(@ModelAttribute("addressBook")AdressBook addressBook,@RequestParam("id") int id, Locale locale, Model model) {
		logger.info("redirect to editContact things");
		if(addressBook == null)
			model.addAttribute("addressBook", this.addressBook);
		
		if(id==-1)
		{
			logger.info("new");
			curentContact=new Contact();
		}
		else
		{
			if(id<addressBook.getContactList().size()&&id>-1)
				curentContact=addressBook.getContactById(id);
			logger.info("id");
		}
		if(curentContact==null)
		{
			logger.info("new");
			curentContact=new Contact();
		}
		model.addAttribute("contact", curentContact);
		model.addAttribute("adress0",curentContact.getPaymentAdress());
		
		List<Adress> list=curentContact.getDeliveryAdress();
		logger.info(""+list.size());
		model.addAttribute("deliveryAdress", list);
		for(int i=1;i<=list.size();i++){
			logger.info("i="+i);
			model.addAttribute("adress"+i, list.get(i-1));
		}
		model.addAttribute("id",id);
		return "pages/editContact";
	}
	
	@RequestMapping(value = "/editContact/addadress")
	public String newAdress( Locale locale, Model model) {
		if(curentContact==null)
		{
			logger.info("new");
			curentContact=new Contact();
		}
		Adress a=new Adress();
		a.setId(curentContact.getDeliveryAdress().size());
		curentContact.addDeliveryAddress(a);
		logger.info("new address");
		return "redirect:../editContact?id="+curentContact.getId();
		
	}
	
	@RequestMapping(value = "/contact")
	public String newContact(@RequestParam("id") int id,Locale locale, Model model) {
		Contact c=addressBook.getContactById(id);
		logger.info("id="+id);
		
		model.addAttribute("id",c.getId());
		model.addAttribute("firstName",c.getFirstName());
		model.addAttribute("secondName",c.getSecondName());
		model.addAttribute("phoneNumber",c.getPhoneNumber());
		model.addAttribute("email",c.getEmail());
		model.addAttribute("active",c.getActive());
		model.addAttribute("birthDate",c.getBirthDate());
		model.addAttribute("paymentAddress",c.getPaymentAdress());
		model.addAttribute("deliveryAddressList", c.getDeliveryAdress());		
		
		logger.info(c.getFirstName()+c.getSecondName());
		return "pages/contactInfo";
	}
	
	
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String edit(@ModelAttribute("contact")Contact contact ,@ModelAttribute("PaymentAddress") Adress payAdress, Locale locale, Model model) {
		logger.info("editing things"); 
		logger.info(contact.getFirstName()+contact.getSecondName()+contact.getBirthDate()+contact.getEmail()); 
		logger.info(contact.getDeliveryAdress().toString());
		logger.info(payAdress.toString());
		contact.setDeliveryAdress(curentContact.getDeliveryAdress());
		contact.setPaymentAdress(curentContact.getPaymentAdress());
		addressBook.removeContactById(contact.getId());
		addressBook.getContactList().add(contact.getId(),contact);
		curentContact=contact;
		
		return"redirect:editContact?id="+contact.getId();
	}
	
	/*@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String editredirect(@ModelAttribute("addressBook")AdressBook addressBook, Locale locale, Model model) {
		logger.info("redirect to editContact things");
		
		if(addressBook != null)
			model.addAttribute("modelTest", this.addressBook);
		if(model.containsAttribute("id"))
		{
			Contact contact=addressBook.getContactById((Integer) model.asMap().get("id"));
			model.addAttribute("contact", contact);
			model.addAttribute("Adress0",contact.getPaymentAdress());
			List<Adress> list=contact.getDeliveryAdress();
			model.addAttribute("deliveryAdress", list);
		}
		else
		{
			Contact contact=new Contact();
			model.addAttribute("contact", contact);
			model.addAttribute("paymentAdress",contact.getPaymentAdress());
			List<Adress> list=contact.getDeliveryAdress();
			model.addAttribute("deliveryAdress", list);
		}
		return "pages/editContact";
	}*/
	
	
	
	@RequestMapping(value = "/editAddress", method = RequestMethod.POST)
	public String editaddress(@ModelAttribute("adress")Adress address , Locale locale, Model model) {
		
		if(address.getId()==-1){
			curentContact.setPaymentAdress(address);
			logger.info("editing payment "+address.getId()); 
		}
		else
		{
			curentContact.getDeliveryAdress().remove(address.getId());
			curentContact.getDeliveryAdress().add(address.getId(),address);
			logger.info("editing delivery "+address.getId()); 
		}
		return"redirect:editContact?id="+curentContact.getId();
	}
	
	
	@RequestMapping("/*")
	public String defaultresponse(Locale locale, Model model) {
		logger.info("default get request handler?");
		
		//TODO add page not found!
		return "index";
	}

	@ModelAttribute("addressBook")
	public AdressBook getAddressBook() {
		return addressBook;
	}

	public void setAddressBook(AdressBook addressBook) {
		this.addressBook = addressBook;
	}

	
}
